<?php
require_once 'ctlAbstract.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

/**
 * 
 * This class controls login functions
 * @author Minh-Tuan
 *
 */
class LoginController extends AbstractController {
	private $_userBus;
	/**
	 * This function will be called by the router
	 */
	public function main(array $getVars) {
		global $ubi;
		//start a session
		//session_start();
		
		//if there is data from the form
		if (isset($_POST['name']) && isset($_POST['pass'])) {
			$username = $_POST['name'];
			$password = $_POST['pass'];
			
			$_userBus = new UserBus();
			$ipAddress = isset($_COOKIE[$ubi['SITE']['IP_COOKIENAME']])?$_COOKIE[$ubi['SITE']['IP_COOKIENAME']]:null;			
			$user = $_userBus->login($username, $password, $ipAddress);
			if (!isset($_COOKIE[$ubi['SITE']['IP_COOKIENAME']])) {
				setcookie($ubi['SITE']['IP_COOKIENAME'], $user->getIpAddress());
			}	
			if ($user) {
				if ($user->getStatus() == 1) {
					//user has logged in successfully				
					//create session
					$_SESSION['userid'] = $user->getUserID();
					$_SESSION['username'] = $user->getUserName();
					$_SESSION['email'] = $user->getEmail();
					$_SESSION['roleid'] = $user->getRoleID();
					$_SESSION['rem'] = false;				
					
					if (isset($_POST['chkRemember']) && $_POST['chkRemember'] == 'on') {
						//set cookie
						setcookie($ubi['SITE']['COOKIE_USERNAME'], $username);
						setcookie($ubi['SITE']['COOKIE_PASSWORD'], $password);
						$_SESSION['rem'] = true;
					} else {
						//delete cookie
						setcookie($ubi['SITE']['COOKIE_USERNAME'], '', time() - 3600);
						setcookie($ubi['SITE']['COOKIE_PASSWORD'], '', time() - 3600);
					}
					
					//display the notice
					$notice = "LoginSuccessfully";
					
					echo $user->getFirstName() . ' ' . $user->getLastName();
				} else {
					echo $ubi['SERVER']['ACCOUNT_NOT_ACTIVATE'];	
				}							
			} else {
				//put error to variable
				$err = 'Bạn đã đăng nhập với tài khoản hoặc mật khẩu không chính xác!';				
			}
		} else {
			//check to see if a user has logged in
			if (isset($_SESSION['userid']) && $_SESSION['userid']) {
				//the user has logged in, redirect him to the index page				
				header('Location:' . 'index.php');
			} else {
				//the user hasn't logged in, display the login page
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewLogin.php';
			}
		}
	}
}
?>